import { defineStore } from 'pinia';
import { distributorLogin, fetchUserInfo, signOut, changePassword, updateHeader } from '@/api/member';
import type { ChangePasswordPayload, UserInfo, UpdateHeaderPayload } from '@/api/member';
import { useEnumStore } from './enum';

interface StoreUserState {
  token: string;
  info: UserInfo | null;
}

const TOKEN_KEY = import.meta.env.VITE_TOKEN_KEY || 'app-token';

export const useUserStore = defineStore('user', {
  state: (): StoreUserState => ({
    token: localStorage.getItem(TOKEN_KEY) || '',
    info: null,
  }),
  getters: {
    isLoggedIn(state): boolean {
      return Boolean(state.token);
    },
    userInfo(state): UserInfo | null {
      return state.info;
    },
  },
  actions: {
    setToken(token: string) {
      this.token = token;
      if (token) {
        localStorage.setItem(TOKEN_KEY, token);
      } else {
        localStorage.removeItem(TOKEN_KEY);
      }
    },
    setInfo(info: UserInfo | null) {
      this.info = info;
    },
    async login(account: string, password: string) {
      const token = await distributorLogin({ account, password });
      this.setToken(token);
      await this.getUserInfo();
      // 登录成功后拉取并缓存枚举数据（只拉一次）
      const enumStore = useEnumStore();
      await enumStore.loadAllEnums();
      return token;
    },
    async getUserInfo() {
      const info = await fetchUserInfo();
      this.setInfo(info);
      return info;
    },
    async logout() {
      try {
        await signOut();
      } catch (error) {
        console.error('退出登录失败', error);
      } finally {
        this.setToken('');
        this.setInfo(null);
      }
    },
    async updatePassword(payload: ChangePasswordPayload) {
      return await changePassword(payload);
    },
    async updateUserHeader(payload: UpdateHeaderPayload) {
      await updateHeader(payload);
      // 更新成功后重新获取用户信息
      await this.getUserInfo();
    },
  },
  persist: {
    pick: ['token'],
    storage: localStorage,
  },
});
